﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using YoProgramo.Infrastructure.Data.NHIbernate;

namespace YoProgramo.Infrastructure.Data
{
    public class DAOBase<TEntity, TYpe, Tid> {
        public ISession session;

        public DAOBase()
        {            
            session = NHWrapper.GetCurrentSession();
        }

        public DAOBase(ISession NHsession) {
            session = NHsession;
        }

        public TEntity GetById(Tid id) {
            return session.Get<TEntity>(id);//typeof(TYpe), 
        }

        public void Delete(TYpe obj) {
            session.Delete(obj);
            session.Flush();
        }

        public void Save(TYpe obj) {
            session.Save(obj);
            session.Flush();
        }

        public void SaveOrUpdate(TYpe obj) {
            session.SaveOrUpdate(obj);
            session.Flush();
        }


        public IList<TYpe> GetAll(int pageIndex, int pageSize) {
            ICriteria criteria = session.CreateCriteria(typeof(TYpe));
            criteria.SetFirstResult(pageIndex * pageSize);
            if (pageSize > 0) {
                criteria.SetMaxResults(pageSize);
            }
            return criteria.List<TYpe>();
        }

        public IList<TYpe> GetAll() {
            return GetAll(0, 0);
        }
    }
}